import { NameSpace } from 'utils/index';
import exceed from 'utils/apimap';
import { ENUM } from 'utils/constants';
import { Message } from '@teamix/ui';
import intl from '../../../../../../../../../locale';

const { backupTypes } = ENUM;

const ns = NameSpace('backup');
export const UPDATE_DATA = ns('UPDATE_DATA');
export const RESET_DATA = ns('RESET_DATA');

const { organization } = window.FORCE;

export function updateData(data) {
  return (dispatch) => {
    dispatch({
      type: UPDATE_DATA,
      data,
    });
  };
}

export function resetData() {
  return (dispatch) => {
    dispatch({
      type: RESET_DATA,
    });
  };
}

/**
 * 获取信息
 * @param {*} noLoadng 定时刷新时，不需要loading
 */
let timer = null;
export function getBackupSpaceInfo(noLoadng) {
  return (dispatch) => {
    if (!noLoadng) {
      dispatch(
        updateData({
          isLoading: true,
        }),
      );
    }

    exceed
      .fetch({
        api: 'org.backup.spaceInfo',
        params: {
          org_id: organization.id,
        },

        data: {
          type: backupTypes.oss,
        },
      })
      .then((result) => {
        if (result.is_has_pending_back_up) {
          timer = setTimeout(() => {
            dispatch(getBackupSpaceInfo(true));
          }, 30000);
        } else {
          clearTimeout(timer);
        }
        dispatch(
          updateData({
            backupSpaceInfo: result,
            isLoading: false,
            formInitData: {
              location: result.space_location || '',
              name: result.space_name || '',
            },

            isManualPending: result.is_has_pending_back_up,
          }),
        );

        // 非定时查询，获取bucket name
        if (!noLoadng && result.space_location) {
          dispatch(getBucketNames(result.space_location));
        }
      })
      .fail((err) => {
        console.error(err);
        dispatch(
          updateData({
            isLoading: false,
            isManualPending: false,
          }),
        );
      });
  };
}

/**
 * 清除定时器
 */
export function clearTimer() {
  return () => {
    clearTimeout(timer);
  };
}

/**
 * 授权
 * @param {*} role
 */
export function backupAuthorize(role) {
  return (dispatch) => {
    dispatch(
      updateData({
        isAuthorizing: true,
      }),
    );

    exceed
      .fetch({
        api: 'org.backup.authorize',
        params: {
          org_id: organization.id,
        },

        data: {
          type: backupTypes.oss,
          role,
        },
      })
      .then(() => {
        Message.success({
          title: intl.get({
            id: 'code-assets.backup.actions.ServiceAuthorizationCreated',
            defaultMessage: '服务授权创建成功',
          }),
        });
        dispatch(
          updateData({
            isAuthorizing: false,
          }),
        );

        dispatch(getBackupSpaceInfo());
      })
      .fail((err) => {
        console.error(err);
        dispatch(
          updateData({
            isAuthorizing: false,
          }),
        );
      });
  };
}

/**
 * 解除授权
 * @param {*} service_authorization_id
 */
export function removeBackupAuth(service_authorization_id) {
  return (dispatch) => {
    updateData({
      isRemovingAuth: true,
    })(dispatch);
    exceed
      .fetch({
        api: 'org.backup.removeAuth',
        params: {
          org_id: organization.id,
        },

        data: {
          type: backupTypes.oss,
          service_authorization_id,
        },
      })
      .then(() => {
        dispatch(
          updateData({
            isRemovingAuth: false,
          }),
        );

        dispatch(getBackupSpaceInfo());
      })
      .fail(() => {
        updateData({
          isRemovingAuth: false,
        })(dispatch);
      });
  };
}

/**
 * 创建备份空间
 * @param {*} data
 */
export function createBackupSpace(data) {
  return (dispatch) => {
    updateData({
      isCreatingSpace: true,
    })(dispatch);
    exceed
      .fetch({
        api: 'org.backup.sapce.create',
        params: {
          org_id: organization.id,
        },

        data: {
          ...data,
          type: backupTypes.oss,
        },
      })
      .then(() => {
        dispatch(
          updateData({
            isCreatingSpace: false,
          }),
        );

        dispatch(getBackupSpaceInfo());
      })
      .fail(() => {
        updateData({
          isCreatingSpace: false,
        })(dispatch);
      });
  };
}

/**
 * 获取bucket名称
 * @param {*} space_location
 */
export function getBucketNames(space_location) {
  return (dispatch) => {
    updateData({
      isLoadingBucketNames: true,
    })(dispatch);

    exceed
      .fetch({
        api: 'org.backup.space.meta',
        params: {
          org_id: organization.id,
        },

        data: {
          type: backupTypes.oss,
          space_location,
        },
      })
      .then((result) => {
        dispatch(
          updateData({
            bucketNames: result ? result.space_name_list : [],
            isLoadingBucketNames: false,
          }),
        );
      })
      .fail((err) => {
        console.error(err);
        dispatch(
          updateData({
            isLoadingBucketNames: false,
          }),
        );
      });
  };
}

/**
 * 定时备份开关和修改空间
 * @param {*} data： { space_id，is_open_auto_back_up， space_location, space_name }
 */
export function updateBackupSpace(data) {
  return (dispatch) => {
    updateData({
      isToggleSetting: true,
    })(dispatch);

    exceed
      .fetch({
        api: 'org.backup.space.updateSettings',
        params: {
          org_id: organization.id,
        },

        data,
      })
      .then(() => {
        dispatch(
          updateData({
            isToggleSetting: false,
          }),
        );

        Message.success({
          title: intl.get({
            id: 'code-assets.backup.actions.TheBackupSettingsHaveBeen',
            defaultMessage: '修改备份设置成功',
          }),
        });

        dispatch(getBackupSpaceInfo(true));
      })
      .fail((err) => {
        console.error(err);
        dispatch(
          updateData({
            isToggleSetting: false,
          }),
        );
      });
  };
}

/**
 * 手动备份开关
 */
export function manualBackup() {
  return (dispatch) => {
    updateData({
      isManualPending: true,
    })(dispatch);

    exceed
      .fetch({
        api: 'org.backup.manual',
        params: {
          org_id: organization.id,
        },
      })
      .then(() => {
        dispatch(getBackupSpaceInfo(true));
      })
      .fail((err) => {
        console.error(err);
        dispatch(
          updateData({
            isManualPending: false,
          }),
        );
      });
  };
}
